package com.imooc.utils;

import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * FileName: ValidateUtil.java
 * Description: TODO
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/31
 */
public final class ValidateUtil {

    private ValidateUtil() {}

    /**
     * 实体校验
     *
     * @param obj
     */
    public static <T> void validate(T obj) {
        Validator validator = SellContextHelper.getBean(Validator.class);
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, new Class[0]);
        if (constraintViolations.size() > 0) {
            ConstraintViolation<T> validateInfo = (ConstraintViolation<T>) constraintViolations.iterator().next();
            // validateInfo.getMessage() 校验不通过时的信息，即message对应的值
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), validateInfo.getMessage());
        }
    }

    public static <T> void validate(T obj, Class<?>... classes) {
        Validator validator = SellContextHelper.getBean(Validator.class);
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, classes);
        if (constraintViolations.size() > 0) {
            ConstraintViolation<T> validateInfo = (ConstraintViolation<T>) constraintViolations.iterator().next();
            // validateInfo.getMessage() 校验不通过时的信息，即message对应的值
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), validateInfo.getMessage());
        }
    }
}
